package com.financing.wap.web.controller.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.bcel.generic.ARRAYLENGTH;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.wap.common.Pager;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.CorpFaUserDTO;
import com.financing.wap.dto.FaUserWechatDTO;
import com.financing.wap.dto.FpClientActivityDTO;
import com.financing.wap.dto.FpClientActivityUserDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFpClientActivityService;
import com.financing.wap.service.IFpClientActivityUserService;
import com.financing.wap.service.ISmsNewService;
import com.financing.wap.service.IUserService;
import com.financing.wap.service.IUserWechatService;
import com.financing.wap.util.StringUtil;
import com.financing.wap.web.controller.BaseController;

@Controller("fpClientActivityUserController")
@RequestMapping("/api/fpClientActivityUser")
public class FpClientActivityUserController extends BaseController  { 

	private Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private IFpClientActivityUserService fpClientActivityUserService;
	
	@Autowired
	private IFpClientActivityService fpClientActivityService;
	
	@Autowired
	private IUserWechatService userWechatService;
	
	@Autowired
	private ISmsNewService smsNewService;
	
	@Autowired
	private IUserService userService;
	/***
	 * 
	
	* @Title: list
	
	* @Description:查询某活动的报名人
	
	* @param @param request
	* @param @param fpClientActivityUser
	* @param @param pager
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/listFpClientActivityUser")
	@ResponseBody
	public ResultMap list(HttpServletRequest request, FpClientActivityUserDTO fpClientActivityUser,Pager pager){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("query fpClientActivityUser list begin .......");
			
			fpClientActivityUser.setBegin(pager.getStartIndex());
			fpClientActivityUser.setPageSize(pager.getPageSize());
			
			// 只有登录人查看自己的活动
			UserDTO u=SessionUtil.getSession().getUser();
			if(null == u){
				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			//查询活动id
			Integer activityId = fpClientActivityUser.getActivityId();
			if(activityId==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			FpClientActivityDTO aUDto = fpClientActivityService.loadById(activityId);
			if(aUDto.getUserId()==null||!aUDto.getUserId().equals(u.getId())){
				result.setAttribute("pager", pager);
				result.setAttribute("list", Collections.EMPTY_LIST);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				result.setStatus(ResultMap.STATUS.SUCCESS);
			}
			
			int count = fpClientActivityUserService.queryListCount(fpClientActivityUser);
			
			pager.setTotalCount(count);
			
			List<FpClientActivityUserDTO> fpClientActivityUserList = null;
			
			if(count > 0){
				fpClientActivityUserList = fpClientActivityUserService.queryList(fpClientActivityUser);
			}else{
				fpClientActivityUserList = Collections.emptyList();
			}
			result.setAttribute("pager", pager);
			result.setAttribute("list", fpClientActivityUserList);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("query fpClientActivityUser list end .......");
		}catch(Exception e){
			log.error("query fpClientActivityUser error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
	/***
	 * 
	
	* @Title: add
	
	* @Description: 用户参加活动
	
	* @param @param request
	* @param @param fpClientActivityUser
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/addFpClientActivityUser")
	@ResponseBody
	public ResultMap add(HttpServletRequest request, FpClientActivityUserDTO fpClientActivityUser){
		ResultMap result = new ResultMap();
		
		try{
			logger.info("add fpClientActivityUser  begin .......");
			
			Integer activityId = fpClientActivityUser.getActivityId();
			String userName = fpClientActivityUser.getUserName();
			String userPhone = fpClientActivityUser.getUserPhone();
			
			boolean v=StringUtil.isNullOrEmptyNStr(userName,userPhone);
			if(v||activityId==null){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			boolean isMobile=StringUtil.isMobile(userPhone);
			if(!isMobile){
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_VALIDATE_ERROR);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
//			UserDTO u=SessionUtil.getSession().getUser();
//			if(null == u){
//				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
//				result.setStatus(ResultMap.STATUS.FAILE);
//				return result;
//			}
			
			fpClientActivityUser.setUserId(userPhone);
			// 同一个活动，一个用户只能参加一次
			FpClientActivityUserDTO tempDTO = new FpClientActivityUserDTO();
			tempDTO.setActivityId(activityId);
			tempDTO.setUserPhone(userPhone);
			if(fpClientActivityUserService.queryListCount(tempDTO) > 0){
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITY_REPEAT_ADD);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			
			//查看活动是否已经开始  
			// update by cmo 以活动结束时间为准，只要活动没结束，都可报名
			FpClientActivityDTO activity = fpClientActivityService.loadById(activityId);
			if(activity.getId()==null){
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_REGISTTIME_END);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			Date activityEndDate = activity.getActivityEndDate();
			if(new Date().after(activityEndDate)){
				result.setStatusCode(ResultMap.STATUS_CODE_ACTIVITIES_REGISTTIME_END);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}
			String wechatId = (String) SessionUtil.getSession(true).getAttribute(WeixinController.OPENID);
			if(StringUtils.isNotBlank(wechatId)){
				 FaUserWechatDTO faUserWechatDTO = new FaUserWechatDTO();
				// 根据userId获取用户头像
				faUserWechatDTO.setMpOpenid(wechatId);
	            FaUserWechatDTO view = userWechatService.queryUserWechatInfo(faUserWechatDTO);
	            if(view != null){
	            	fpClientActivityUser.setUserImg(view.getHeadimgurl());
	            }
			}
			
			int id = fpClientActivityUserService.insert(fpClientActivityUser);
			result.setAttribute("id", id);
			try {
				//发送短信
				String content="有用户报名了您的活动【%s】，客户姓名【%s】，手机号码【%s】请及时处理";
				content=String.format(content, activity.getActivityTitle(),userName,userPhone);
				List mobileList=new ArrayList<String>();
				mobileList.add(activity.getUserId());
				smsNewService.sendSms(mobileList,content,"ClientActivitySendSms");
			} catch (Exception e) {
				log.error(" ClientActivitySendSms send error!",e);
			}
			
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			
			logger.info("add fpClientActivityUser list end .......");
		}catch(Exception e){
			log.error("add fpClientActivityUser error!",e);
			result.setStatus(ResultMap.STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		
		return result;
	}
	
}
